﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;
using QRCoder;//需要在项目->管理NuGetchengxbao->安装QRCoder
using Excel = Microsoft.Office.Interop.Excel;//excel 需要

namespace vlcplay
{
    public partial class QRCoder : Form
    {
        ProgressBarText ProgressBarT = new ProgressBarText();//创建进度条上面的文字
        public QRCoder()
        {
            InitializeComponent();
        }

        private void btn_choice_Click(object sender, EventArgs e)
        {
            textBox_file_name.Text = string.Empty;

            #region 选择文件
            OpenFileDialog sfd = new OpenFileDialog();
            //默认显示名称
            //sfd.FileName = "sqlite.db";
            //设置匹配文件格式，可包含多种
            sfd.Filter = "Excel(*.xlsx)|*.xlsx";
            //sfd.Filter = "数据库文件(*.db)|*.db";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                textBox_file_name.Text = sfd.FileName;
            }
            else
            {
                return;
            }
            #endregion
        }
        /// <summary>
        /// 生成单个二维码
        /// </summary>
        private void RenderQrCode()
        {
            string level = "0";//comboBoxECC.SelectedItem.ToString();
            QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level == "L" ? 0 : level == "M" ? 1 : level == "Q" ? 2 : 3);
            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            {
                using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(textBoxQRCode.Text, eccLevel))
                {
                    using (QRCode qrCode = new QRCode(qrCodeData))
                    {
                        //1、二维码单个像素点的大小 2、像素颜色 3、背景颜色 4、接收一个 Bitmap，用来设置二维码中间那个图标5、图标大小百分比6、图标边框宽度，7、边缘留白
                        //pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(15, Color.Black, Color.White, null, 10, 1, true) ;
                        pictureBoxQRCode.Image = qrCode.GetGraphic(15, Color.Black, Color.White, null, 10, 1, true);
                        this.pictureBoxQRCode.Size = new System.Drawing.Size(pictureBoxQRCode.Width, pictureBoxQRCode.Height);
                        
                        //Set the SizeMode to center the image.
                        //this.pictureBoxQRCode.SizeMode = PictureBoxSizeMode.CenterImage;
                        //pictureBoxQRCode.SizeMode = PictureBoxSizeMode.StretchImage;
                    }
                }
            }
        }
        /// <summary>
        /// 将指定数据（name）生成二维码到指定位置（QRimgPath）
        /// </summary>
        /// <param name="name"></param>
        /// <param name="QRimgPath"></param>
        private void SingleQrCode(string name, string QRimgPath)
        {
            string level = "0";//comboBoxECC.SelectedItem.ToString();
            QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level == "L" ? 0 : level == "M" ? 1 : level == "Q" ? 2 : 3);
            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            {
                using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(name, eccLevel))
                {
                    using (QRCode qrCode = new QRCode(qrCodeData))
                    {
                        //1、二维码单个像素点的大小 2、像素颜色 3、背景颜色 4、接收一个 Bitmap，用来设置二维码中间那个图标5、图标大小百分比6、图标边框宽度，7、边缘留白
                        //pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(15, Color.Black, Color.White, null, 10, 1, true) ;
                        Bitmap QRimage = qrCode.GetGraphic(15, Color.Black, Color.White, null, 10, 1, true);
                        QRimage.Save(QRimgPath);
                    }
                }
            }
        }
        /// <summary>
        /// 初始化进度条
        /// </summary>
        /// <param name="max"></param>
        private void Display_progressbar_init(int max)
        {
            this.QRprogressBar.Value = 0;
            this.QRprogressBar.Minimum = 0;
            this.QRprogressBar.Maximum = max;

            ProgressBarT.Font = Font;
            ProgressBarT.Text = "0/0";
            ProgressBarT.ForeColor = Color.Blue;
            ProgressBarT.Control = QRprogressBar;
        }
        /// <summary>
        /// 生成多个二维码
        /// </summary>
        private void MultiRenderQrCode(string filename)
        {
            int comp_count = 0;
            Excel.Application excelAPP = new Excel.Application();
            Excel.Workbook excelWorkbook = excelAPP.Workbooks.Open(filename);//文件地址
            Excel.Worksheet excelWorksheet = excelWorkbook.Sheets[1];
            Excel.Range excelRange = excelWorksheet.UsedRange;
            Display_progressbar_init(excelRange.Count);
            //MessageBox.Show("行列总数："+excelRange.Count.ToString() + "\n" +"列数"+ excelRange.Columns.Count +"\n" +"行数"+ excelRange.Rows.Count);
            QRtext.Text = "转换中：" + "总列数：" + excelRange.Columns.Count + "总行数：" + excelRange.Rows.Count;
            for (int i = 1; i <= excelRange.Rows.Count; i++)//行数
            {
                for (int j = 1; j <= excelRange.Columns.Count; j++)
                {
                    comp_count++;
                    this.QRprogressBar.Value = comp_count;
                    ProgressBarT.Text = comp_count.ToString() + "\\" + excelRange.Count.ToString();

                    //Excel.Range QRcell = excelRange.Cells[i, 1];//获取第一列数据
                    //string QRname = QRcell.Text.ToString();//获取第一列数据

                    Excel.Range QRWritneCell = excelRange.Cells[i, j];//直接生成二维码写入第一列
                    if (QRWritneCell.Text != "")
                    {
                        string QRname = QRWritneCell.Text.ToString();
                        string QRimgPath = "QRimg.jpg";
                        SingleQrCode(QRname, QRimgPath);

                        //Excel.Range QRWritneCell = excelRange.Cells[i, 2];//获取第二列
                        //excelWorksheet.Cells[i,2] = QRname;//在第二列写内容
                        QRWritneCell.ColumnWidth = 30; //列宽
                        QRWritneCell.RowHeight = 160;  //行高
                        QRWritneCell.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平居中
                        QRWritneCell.VerticalAlignment = Excel.XlVAlign.xlVAlignBottom;//垂直居下

                        string localQRimgPath = Environment.CurrentDirectory + "\\" + QRimgPath; //获取二维码地址
                                                                                                 //MessageBox.Show(localQRimgPath);
                                                                                                 //将图片加入到excel中
                        excelWorksheet.Shapes.AddPicture(localQRimgPath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, (float)QRWritneCell.Left, (float)QRWritneCell.Top, (float)QRWritneCell.Width, (float)(QRWritneCell.Height - 15));
                    }
                }
            }
            string NewFileName = Path.ChangeExtension(filename,null);//带路径文件名，去除后缀
            NewFileName = NewFileName +"qrcoder"+ ".xlsx";
            string NewFilrName1 = Path.GetFileNameWithoutExtension(NewFileName);//不带路径的文件名，去除后缀
            //MessageBox.Show("文件名："+ NewFileName);
            excelWorkbook.SaveAs(NewFileName);
            excelWorkbook.Close(false);
            excelAPP.Quit();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelRange); ;
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorksheet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelAPP);

            QRtext.Text = "转换完成!!";
            //MessageBox.Show("二维码生成完成！！");
            //Console.ReadKey();
        }
        /// <summary>
        /// 将生成的二维码以指定的格式保存到指定位置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_save_Click(object sender, EventArgs e)
        {
            // Displays a SaveFileDialog so the user can save the Image
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "Bitmap Image|*.bmp|PNG Image|*.png|JPeg Image|*.jpg|Gif Image|*.gif";
            saveFileDialog1.Title = "Save an Image File";
            saveFileDialog1.ShowDialog();

            // If the file name is not an empty string open it for saving.
            if (saveFileDialog1.FileName != "")
            {
                // Saves the Image via a FileStream created by the OpenFile method.
                using (FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile())
                {
                    // Saves the Image in the appropriate ImageFormat based upon the
                    // File type selected in the dialog box.
                    // NOTE that the FilterIndex property is one-based.

                    ImageFormat imageFormat = null;
                    switch (saveFileDialog1.FilterIndex)
                    {
                        case 1:
                            imageFormat = ImageFormat.Bmp;
                            break;
                        case 2:
                            imageFormat = ImageFormat.Png;
                            break;
                        case 3:
                            imageFormat = ImageFormat.Jpeg;
                            break;
                        case 4:
                            imageFormat = ImageFormat.Gif;
                            break;
                        default:
                            throw new NotSupportedException("File extension is not supported");
                    }
                    //pictureBoxQRCode.BackgroundImage.Save(fs, imageFormat);
                    pictureBoxQRCode.Image.Save(fs, imageFormat);
                    fs.Close();
                }
            }
        }
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_create_Click(object sender, EventArgs e)
        {
            try
            {
                RenderQrCode();
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成二维码失败！");
            }
        }
        /// <summary>
        /// 将excel文件的第一列数据生成二维码到第二列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_mulit_save_Click(object sender, EventArgs e)
        {
            if (textBox_file_name.Text == "")
            {
                MessageBox.Show("选择有效文件");
                return; 
            }
            QRtext.Text = "准备转换";
            btn_choice.Enabled = false;
            btn_create.Enabled = false;
            btn_mulit_save.Enabled = false;
            btn_save.Enabled = false;
            MultiRenderQrCode(textBox_file_name.Text);
            btn_choice.Enabled = true;
            btn_create.Enabled = true;
            btn_mulit_save.Enabled = true;
            btn_save.Enabled = true;
        }
    }
}
